﻿using System;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI.WebControls;

namespace Salient.Web.Administration.Security.Users
{
    public partial class manageUsers : SecurityPage
    {
        private const string DATA_SOURCE = "WebAdminDataSource";
        private const string DATA_SOURCE_ROLES = "WebAdminDataSourceRoles";

        public void SetDataSourceRoles(object v)
        {
            Session[DATA_SOURCE_ROLES] = v;
        }

        public void SetDataSource(object v)
        {
            Session[DATA_SOURCE] = v;
        }

        public void BindGrid(bool displayUsersNotCreated)
        {
            DataGrid.DataSource = Session[DATA_SOURCE];
            DataGrid.DataBind();
            if (DataGrid.Rows.Count == 0)
            {
                if (displayUsersNotCreated)
                {
                    noUsers.Visible = true;
                }
                else
                {
                    notFoundUsers.Visible = true;
                }
            }
        }

        public void IndexChanged(object sender, GridViewPageEventArgs e)
        {
            DataGrid.PageIndex = e.NewPageIndex;
            BindGrid(false);
        }

        public void Page_Load()
        {
            noUsers.Visible = false;
            if (!IsPostBack)
            {
                PopulateRepeaterDataSource();
                AlphabetRepeater.DataBind();

                int total = 0;
                var users =
                    (MembershipUserCollection)
                    CallWebAdminHelperMethod(true, "GetAllUsers", new object[] {0, Int32.MaxValue, total},
                                             new[] {typeof (int), typeof (int), Type.GetType("System.Int32&")});
                string[] roles = null;
                if (IsRoleManagerEnabled())
                {
                    roles = (string[]) CallWebAdminHelperMethod(false, "GetAllRoles", new object[] {}, null);
                }

                SetDataSourceRoles(roles);
                SetDataSource(users);
                BindGrid(true);
                DataGrid.HeaderStyle.HorizontalAlign = DirectionalityHorizontalAlign;
            }
        }

        public void ButtonClick(object sender, EventArgs e)
        {
            var button = (LinkButton) sender;
            string userName = button.CommandArgument;
            SetCurrentUser(userName);
        }

        public void EnabledChanged(object sender, EventArgs e)
        {
            var checkBox = (CheckBox) sender;
            var item = (GridViewRow) checkBox.Parent.Parent;
            var label = (Label) item.FindControl("UserNameLink");
            string userID = label.Text;
            var user =
                (MembershipUser)
                CallWebAdminHelperMethod(true, "GetUser", new object[] {userID, false /* isOnline */},
                                         new[] {typeof (string), typeof (bool)});
            user.IsApproved = checkBox.Checked;

            string typeFullName = "System.Web.Security.MembershipUser, " + typeof (HttpContext).Assembly.GetName();
            ;
            Type tempType = Type.GetType(typeFullName);

            CallWebAdminHelperMethod(true, "UpdateUser", new object[] {user}, new[] {tempType});
        }

        public void LinkButtonClick(object sender, CommandEventArgs e)
        {
            if (e.CommandName.Equals("EditUser"))
            {
                CurrentUser = ((string) e.CommandArgument);
                // do not prepend ~/ to this path since it is not at the root
                Response.Redirect("editUser.aspx");
            }
            if (e.CommandName.Equals("DeleteUser"))
            {
                UserID.Text = (string) e.CommandArgument;
                AreYouSure.Text = String.Format((string) GetLocalResourceObject("AreYouSure"), UserID.Text);
                ((WebAdminWithConfirmation) Master).SetDisplayUI(true);
            }
        }

        public void No_Click(object sender, EventArgs e)
        {
            ((WebAdminWithConfirmation) Master).SetDisplayUI(false);
        }

        private void PopulateRepeaterDataSource()
        {
            PopulateRepeaterDataSource(AlphabetRepeater);
        }

        public void RedirectToAddUser(object sender, EventArgs e)
        {
            CurrentUser = null;
            // do not prepend ~/ to this path since it is not at the root
            Response.Redirect("adduser.aspx");
        }

        public void RetrieveLetter(object sender, RepeaterCommandEventArgs e)
        {
            MembershipUserCollection users = null;
            RetrieveLetter(sender, e, DataGrid, (string) GetGlobalResourceObject("GlobalResources", "All"), users);
            SetDataSource(DataGrid.DataSource);
            BindGrid(false);
            RolePlaceHolder.Visible = DataGrid.Rows.Count != 0;
        }

        protected void RoleMembershipChanged(object sender, EventArgs e)
        {
            try
            {
                var box = (CheckBox) sender;
                // Array manipulation because cannot use Roles static method (need different appPath).
                string u = CurrentUser;
                string role = box.Text;

                if (box.Checked)
                {
                    CallWebAdminHelperMethod(false, "AddUsersToRoles", new object[] {new[] {u}, new[] {role}},
                                             new[] {typeof (string[]), typeof (string[])});
                }
                else
                {
                    CallWebAdminHelperMethod(false, "RemoveUsersFromRoles", new object[] {new[] {u}, new[] {role}},
                                             new[] {typeof (string[]), typeof (string[])});
                }
            }
            catch
            {
                // Ignore, e.g., user is already in role.
            }
        }

        public void SearchForUsers(object sender, EventArgs e)
        {
            SearchForUsers(sender, e, AlphabetRepeater, DataGrid, SearchByDropDown, TextBox1);
            SetDataSource(DataGrid.DataSource);
            BindGrid(false);
            RolePlaceHolder.Visible = DataGrid.Rows.Count != 0;
        }

        private void SetCurrentUser(string s)
        {
            CurrentUser = s;
            if (IsRoleManagerEnabled())
            {
                CheckBoxRepeater.DataSource = Session[DATA_SOURCE_ROLES];
                CheckBoxRepeater.DataBind();
                if (CheckBoxRepeater.Items.Count > 0)
                {
                    AddToRole.Text = String.Format((string) GetLocalResourceObject("AddToRoles2"), s);
                }
                else
                {
                    AddToRole.Text = (string) GetLocalResourceObject("NoRolesDefined");
                }
            }
            else
            {
                var arr = new ArrayList();
                CheckBoxRepeater.DataSource = arr;
                CheckBoxRepeater.DataBind();
                AddToRole.Text = (string) GetLocalResourceObject("RolesNotEnabled");
            }

            multiView1.ActiveViewIndex = 1;
        }

        public string GetToolTip(string resourceName, string itemName)
        {
            var tempString = (string) GetLocalResourceObject(resourceName);
            return String.Format((string) GetGlobalResourceObject("GlobalResources", "ToolTipFormat"), tempString,
                                 itemName);
        }

        public void Yes_Click(object sender, EventArgs e)
        {
            CallWebAdminHelperMethod(true, "DeleteUser", new object[] {UserID.Text, true},
                                     new[] {typeof (string), typeof (bool)});

            int total = 0;
            var users =
                (MembershipUserCollection)
                CallWebAdminHelperMethod(true, "GetAllUsers", new object[] {0, Int32.MaxValue, total},
                                         new[] {typeof (int), typeof (int), Type.GetType("System.Int32&")});
            string[] roles = null;
            if (IsRoleManagerEnabled())
            {
                roles = (string[]) CallWebAdminHelperMethod(false, "GetAllRoles", new object[] {}, null);
            }

            SetDataSource(users);
            SetDataSourceRoles(roles);
            BindGrid(true);

            PopulateRepeaterDataSource();
            AlphabetRepeater.DataBind();

            ((WebAdminWithConfirmation) Master).SetDisplayUI(false);
        }
    }
}